<template>
  <div class="Register">
    <shop-header>注册</shop-header>
    <shop-logo></shop-logo>
    <van-field
      v-model="username"
      required
      label="用户名"
      placeholder="请输入用户名"
      :error-message="usernameErrMes"
      @input="checkUsername"
    />
    <van-field
      v-model="nickname"
      required
      label="昵称"
      placeholder="请输入昵称"
      :error-message="nicknameErrMes"
      @input="checkNickname"
    />
    <van-field
      v-model="password"
      required
      label="密码"
      placeholder="请输入密码"
      :error-message="passwordErrMes"
      @input="checkPassword"
    />
    <shop-button @click.native="register">注册</shop-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '123444',
      password: '123456',
      nickname: '谢文豪',
      usernameErrMes: '',
      nicknameErrMes: '',
      passwordErrMes: '',
    }
  },
  methods: {
    checkUsername() {
      if (this.username == '') {
        this.usernameErrMes = ''
      } else {
        const reg = /^1\d{3,6}$/
        if (reg.test(this.username)) {
          this.usernameErrMes = ''
        } else {
          this.usernameErrMes = '用户名格式不正确'
        }
      }
    },
    checkNickname() {
      if (this.nickname == '') {
        this.nicknameErrMes == ''
      } else {
        const reg = /^[\u4e00-\u9fa5]{1,5}$/
        if (reg.test(this.nickname)) {
          this.nicknameErrMes = ''
        } else {
          this.nicknameErrMes = '昵称名格式不正确'
        }
      }
    },
    checkPassword() {
      if (this.password == '') {
        this.passwordErrMes = ''
      } else {
        const reg = /^\d{5,12}$/
        if (reg.test(this.password)) {
          this.passwordErrMes = ''
        } else {
          this.passwordErrMes = '密码格式不正确'
        }
      }
    },
    async register() {
      if (
        this.nickname != '' &&
        this.password != '' &&
        this.nickname !== '' &&
        this.usernameErrMes == '' &&
        this.nicknameErrMes == '' &&
        this.passwordErrMes == ''
      ) {
        const res = await this.$axios.post('/register', {
          username: this.username,
          nickname: this.nickname,
          password: this.password,
        })
        // console.log(res);
        const { message, statusCode } = res.data
        console.log(message, statusCode)
        if (statusCode == 200) {
          this.$toast.success(message)
          this.$router.push({
            name: 'login',
            params: { username: this.username, password: this.password },
          })
        } else {
          this.$toast.fail(message)
        }
      }
    },
  },
}
</script>

<style></style>
